<template>
  <ele-modal :width="400" :body-style="{ height: '450px', overflow: 'scroll' }" title="配置菜单" position="center"
    v-model="visible" @open="handelOpen">
    <el-tree ref="treeRef" style="max-width: 400px" :data="moduleTree" show-checkbox node-key="id" highlight-current
      :props="{ label: 'name' }" />
    <template #footer>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </ele-modal>
</template>

<script setup lang="ts">
import { ref } from "vue"
import { EleMessage } from "ele-admin-plus";
import type { TreeInstance } from 'element-plus';
import { queryList } from "@/api/system/SysModule"
import { queryList as querySysTenantModule, edit } from "@/api/system/SysTenantModule";
import type { SysModule } from "@/api/system/SysModule/model";
import type { SysTenant } from "@/api/system/SysTenant/model.ts";

const props = defineProps<{
  tenant: SysTenant | null
}>()

const visible = defineModel({ type: Boolean });
const treeRef = ref<TreeInstance | null>(null)
const moduleTree = ref<SysModule[]>([])

const save = async () => {
  const res = await edit({ tenantId: props.tenant!.id, moduleIdList: treeRef.value?.getCheckedKeys() as string[] })
  if (res.code == 200) {
    EleMessage.success('保存成功')
    visible.value = false
  } else {
    EleMessage.error('保存失败')
  }
}

const handelOpen = async () => {
  const moduleRes = await queryList()
  moduleTree.value = moduleRes.data!
  const res = await querySysTenantModule(props.tenant!.id)
  treeRef.value?.setCheckedKeys(res.data!.map(e => e.moduleId))
}


</script>

<style scoped></style>
